# -*- encoding: utf-8 -*-
import datetime
import logging
import enum
from django.conf import settings
from common.mg_core.mg import get_report_template, insert_or_update, MONGODB
from common.dwc.friday import marketing_handler as handler

_LOGGER = logging.getLogger(__name__)


class ExternalEnum(enum.Enum):
    DailyS2s = 'daily_s2s'
    DailyUser = 'daily_user'
    DailyDevice = 'daily_device'
    DailySummary = 'daily_summary'


handler_map = {
    ExternalEnum.DailyS2s.value: handler.s2s_report_handler_v2,
    ExternalEnum.DailyUser.value: handler.dwc_daily_user_report_v2,
    ExternalEnum.DailyDevice.value: handler.dwc_daily_device_report_v2,
    ExternalEnum.DailySummary.value: handler.dwc_summary_report_v2
}

COLLECTION = 'dwc_external_report'


def create_aggregation_data(idx: str, handler_name: ExternalEnum, time_range, interval_type, filter_config=None):
    now = datetime.datetime.now()
    handler_func = handler_map.get(handler_name.value)
    if filter_config is not None:
        report_key = _get_report_key(handler_name.value, time_range[0], interval_type.value, filtered=True)
        data = handler_func(idx, time_range=time_range,
                            chn_list=filter_config.get('chn_list'),
                            user_channel_ttls=filter_config.get('channel_ttl'),
                            banned_channels=filter_config.get('banned_channels'),
                            banned_user_ids=filter_config.get('banned_user_ids'))
    else:
        report_key = _get_report_key(handler_name.value, time_range[0], interval_type.value)
        data = handler_func(idx, time_range=time_range)
    report_template = get_report_template(time_range[0], interval_type, custom_report_id=report_key)
    report_template.update({
        'updated_at': now,
    })
    report_template.update(data)
    insert_or_update(report_template, idx, collection=COLLECTION)


def get_aggregation_data(database, name: ExternalEnum, time_range, filtered=False, interval_type='day'):
    assert database in settings.DWC_INDEX
    report_key = _get_report_key(name.value, time_range[0], interval_type=interval_type, filtered=filtered)
    data = MONGODB[database][COLLECTION].find_one({'_id': report_key})
    return data


def _get_report_key(name, start_time, interval_type, filtered=False):
    day = str(start_time).split(' ')[0]
    if interval_type == 'day':
        return '_'.join([name, day, 'filtered']) if filtered else '_'.join([name, day])
    else:
        hour = str(start_time).split(':')[0].split(' ')[1]
        return '_'.join([name, day, hour, 'filtered']) if filtered else '_'.join([name, day, hour])
